/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */

const l1 = {
   value: 2,
   next: {
      value: 4,
      next: {
         value: 3,
      }
   }
}

const l2 = {
   value: 5,
   next: {
      value: 6,
      next: {
         value: 4
      }
   }
}

const a2 = [5, 6, 4]

/**
 * 
 * @param {*} linkNode 数组化的对象
 * @param {*} target  是否是第一次
 */

let arr1 = []
function link2Arr(linkNode, target) {
   if (target) {
      arr1 = []
   }
   if (!linkNode) return null
   arr1.push(linkNode.value)
   if (linkNode.next) {
      linkNode = linkNode.next
      link2Arr(linkNode, false)
   }
   return arr1
}

function array2list(ary) {
   if (ary.length === 0) {
      return null
   }
   var nodes = []

   for (var i = 0; i < ary.length; i++) {
      var node = {}
      node.value = ary[i]
      node.next = null
      nodes.push(node)
   }

   for (var i = 0; i < nodes.length - 1; i++) {
      nodes[i].next = nodes[i + 1]
   }

   return nodes[0]
}


//  参数: ListNode. 
function addTwoNumbers(l2, l1) {
   const arr1 = link2Arr(l1)
   const arr2 = link2Arr(l2, true)
   if (!arr1 && !arr2) return null
   if (!arr1) return arr2
   if (!arr2) return arr1
   const length = Math.min(arr1.length, arr2.length)
   let arr3 = []

   for (let i = 0; i < length; i++) {
      let num = arr1[i] + arr2[i]
      //   target 进位符 
      if (target) {
         num += 1
         target = false
      }
      if (num >= 10) {
         num -= 10
         var target = true
      }
      arr3.push(num)
   }
   if (target) {
      if (arr1.length > arr2.length) {
         arr3[length] = 1 + arr1[length]
         arr3 = [...arr3, ...arr1.slice(arr2.length + 1)]
      } else {
         arr3[length] = 1 + arr2[length]
         arr3 = [...arr3, ...arr2.slice(arr1.length + 1)]
      }
   }
   // return arr3
   return array2list(arr3)
}


const result = addTwoNumbers(l1, l2)
console.log(result)